package org.example.shop_front_api.interceptor;

import com.google.gson.Gson;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.shop_front_api.entity.User;
import org.example.shop_front_api.service.UserService;
import org.example.shop_front_api.utils.JsonResult;
import org.example.shop_front_api.utils.JwtUtils;
import org.example.shop_front_api.utils.UserContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;

@Component
public class ShopInterceptor implements HandlerInterceptor {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private JwtUtils jwtUtils;

    // 新增：注入UserService用于查询用户信息
    @Resource
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取请求头中的Authorization
        String authorization = request.getHeader("Authorization");

        // 2. 校验Token格式
        if (authorization == null || !authorization.startsWith("Bearer ")) {
            return handleError(response, 401, "未携带有效Token，请先登录");
        }

        // 3. 提取纯Token
        String token = authorization.substring(7).trim();
        if (token.isEmpty()) {
            return handleError(response, 401, "Token不能为空");
        }

        // 4. 校验Redis中是否存在Token
        String redisToken = stringRedisTemplate.opsForValue().get(token);
        if (redisToken == null) {
            return handleError(response, 401, "Token已失效，请重新登录");
        }

        // 5. 验证Token并获取用户名
        String username;
        try {
            username = jwtUtils.validateTokenAndGetUsername(token);
        } catch (RuntimeException e) {
            return handleError(response, 401, e.getMessage());
        }

        // 6. 根据用户名查询用户信息并存入上下文
        User user = userService.findByUsername(username);
        if (user == null) {
            return handleError(response, 401, "用户不存在，请重新登录");
        }
        UserContext.setUser(user); // 存入上下文

        // 7. 验证通过，放行
        System.out.println("Token验证通过，请求路径：" + request.getRequestURI());
        return true;
    }

    // 新增：请求结束后清理上下文，避免内存泄漏
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.removeUser();
    }

    private boolean handleError(HttpServletResponse response, int code, String msg) throws Exception {
        response.setStatus(code);
        response.setContentType("application/json;charset=utf-8");
        JsonResult errorResult = JsonResult.failed(code, msg);
        try (PrintWriter writer = response.getWriter()) {
            writer.write(new Gson().toJson(errorResult));
            writer.flush();
        }
        return false;
    }
}